package com.example.camelakkaexamples.jettyconshttpprod

import org.apache.camel.Exchange
import akka.actor.Actor._
import akka.actor.{Actor, ActorRef}
import akka.camel._

class HttpConsumer(producer: ActorRef) extends Actor with Consumer {
  def endpointUri = "jetty:http://0.0.0.0:8875/"
  protected def receive = {
    case msg => producer.forward(msg)
  }
}

class HttpProducer(transformer: ActorRef) extends Actor with Producer {
  def endpointUri = "http:akka.io/?bridgeEndpoint=true"
  override protected def receiveBeforeProduce = {
    case msg: Message =>
      msg.setHeaders(msg.headers(Set(Exchange.HTTP_PATH)))
  }
  override protected def receiveAfterProduce = {
    case msg => transformer.forward(msg)
  }
}

class HttpTransformer extends Actor {
  protected def receive = {
    case msg: Failure => self.reply(msg)
    case msg: Message => self.reply(msg.bodyAs[String].replaceAll("Akka ", "AkkaCamelExample "))
  }
}

object CamelAkkaApp extends Application {
  val service = CamelServiceManager.startCamelService
  service.awaitEndpointActivation(3) {
    val httpTransformer = actorOf(new HttpTransformer).start
    val httpProducer = actorOf(new HttpProducer(httpTransformer)).start
    actorOf(new HttpConsumer(httpProducer)).start
  }

}
